{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 独热编码：将每个特征值转换为有一个1和若干个0表示"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import sklearn.preprocessing as sp"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1, 0, 1, 0, 0, 1, 0, 0, 0],\n",
       "       [0, 1, 0, 1, 0, 0, 1, 0, 0],\n",
       "       [1, 0, 0, 0, 1, 0, 0, 1, 0],\n",
       "       [0, 1, 1, 0, 0, 0, 0, 0, 1]], dtype=int32)"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sample = np.array([[1, 3, 2],\n",
    "                    [7, 5, 4],\n",
    "                    [1, 8, 6],\n",
    "                    [7, 3, 9]])\n",
    "\n",
    "\n",
    "#构建独热编码器\n",
    "encoder = sp.OneHotEncoder(sparse=False,\n",
    "                           dtype='int32',\n",
    "                           categories='auto')\n",
    "\n",
    "res = encoder.fit_transform(sample)\n",
    "res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1, 3, 2],\n",
       "       [7, 5, 4],\n",
       "       [1, 8, 6],\n",
       "       [7, 3, 9]])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "encoder.inverse_transform(res)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
